package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckgroupDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.service.CheckgroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CheckgroupServiceImpl implements CheckgroupService {
    @Autowired
    private CheckgroupDao checkgroupDao;

    @Override
    public PageResult queryPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        Page<CheckGroup> page = checkgroupDao.selectByConditon(queryPageBean.getQueryString());


        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkgroupDao.addCheckGroup(checkGroup);
        if(checkitemIds.length > 0){
            checkgroupDao.addCheckGroupAndCheckItemIds(checkGroup.getId(),checkitemIds);
        }
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkgroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return checkgroupDao.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    public void edit(Integer[] checkitemIds, CheckGroup checkGroup) {
        checkgroupDao.deleteCheckGroupAndCheckItemIds(checkGroup.getId());
        checkgroupDao.updateCheckGroup(checkGroup);
        checkgroupDao.addCheckGroupAndCheckItemIds(checkGroup.getId(),checkitemIds);
    }

    @Override
    public void deleteCheckGroupitemById(Integer id) {
        Integer count = checkgroupDao.selectCountByCheckGroupId(id);
        if (count == 0){
            checkgroupDao.deleteCheckGroupAndCheckItemIds(id);
            checkgroupDao.deleteCheckGroupById(id);
        }else {
            throw new BusinessRuntimeException("有套餐正在使用此检查组,无法删除");
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkgroupDao.findAll();
    }
}
